import axios from "axios";
import $store from "../store";
import toLogin from "@libs/login";
import dialog from "@utils/dialog";
import { VUE_APP_API_URL } from "@utils/index";
const instance = axios.create({
  baseURL: VUE_APP_API_URL,
  timeout: 15000
});

const defaultOpt = { login: true };

function baseRequest(options) {
  const token = localStorage.getItem('token');
  const headers = options.headers || {};
  headers["Authori-zation"] = "Bearer " + token;
  options.headers = headers;
  if (options.login && !token) {
    toLogin();
  }
  return instance(options).then(res => {
    console.group(options.url);
    // console.log("%c 请求路径--->", "color: #1ba01b", options.url);
    // console.log("%c 请求方式--->", "color: #1ba01b", options.method);
    // console.log("%c 请求参数--->", "color: #1ba01b", options.params);
    // console.log("%c 返回值--->", "color: #1ba01b", res.data);
    console.groupEnd();
    // console.log('instance-then', res)
    if (res.status == 200) {
      const data = res.data || {};
      if (data.status === 200 || data.status == 400) {
        // console.log('status', 200)
        return Promise.resolve(data);
      }
      if ([410000, 410001, 410002].indexOf(data.status) !== -1) {
        // console.log('status', 410000, 410001, 410002)
        toLogin();
        return Promise.reject(data);
      }
      return Promise.reject({ msg: data.msg, data });
    } else {
      return Promise.reject({ msg: res.msg, res });
    }
  }).catch(error=>{
    // console.log('instance-error', error)
    if (error && error.stack && error.stack.indexOf('timeout') > -1) {
      return Promise.reject({ msg: '请求超时', data: error});
    }
    if (error.data.status == 410000) {
      return Promise.reject(error.data);
    }
  });
}

/**
 * http 请求基础类
 * 参考文档 https://www.kancloud.cn/yunye/axios/234845
 *
 */
const request = ["post", "put", "patch"].reduce((request, method) => {
  /**
   *
   * @param url string 接口地址
   * @param data object get参数
   * @param options object axios 配置项
   * @returns {AxiosPromise}
   */
  request[method] = (url, data = {}, options = {}) => {
    return baseRequest(
      Object.assign({ url, data, method }, defaultOpt, options)
    );
  };
  return request;
}, {});

["get", "delete", "head"].forEach(method => {
  /**
   *
   * @param url string 接口地址
   * @param params object get参数
   * @param options object axios 配置项
   * @returns {AxiosPromise}
   */
  request[method] = (url, params = {}, options = {}) => {
    return baseRequest(
      Object.assign({ url, params, method }, defaultOpt, options)
    );
  };
});

export default request;
